package com.chen.androidstudy.activity;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.base.library.base.BaseVMActivity;
import com.chen.androidstudy.R;
import com.chen.androidstudy.databinding.ActivityRsaSignBinding;
import com.chen.androidstudy.utils.RSA2Util;

import java.security.KeyPair;

/**
 * 非对称加密、解密、验签
 */
public class RSASignActivity extends BaseVMActivity<LocationViewModel, ActivityRsaSignBinding> {

    @Override
    public int getLayoutId() {
        return R.layout.activity_rsa_sign;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            rsa();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void rsa() throws Exception {
        // 生成私钥和公钥
        KeyPair keyPair = RSA2Util.generateKeyPair();
        String publicKeyStr = RSA2Util.encodePublicKeyToBase64(keyPair.getPublic());
        String privateKeyStr = RSA2Util.encodePrivateKeyToBase64(keyPair.getPrivate());

        Log.e("chen","公钥: " + publicKeyStr);
        Log.e("chen","私钥: " + privateKeyStr);

        // 测试加密解密
        String data = "qaz123456.";
        String encryptedData = RSA2Util.encrypt(data, publicKeyStr);
        Log.e("chen","加密后: " + encryptedData);
        String decryptedData = RSA2Util.decrypt(encryptedData, privateKeyStr);
        Log.e("chen","解密后: " + decryptedData);


        // 测试签名和验签
        String signature = RSA2Util.sign(data, privateKeyStr);
        Log.e("chen","签名: " + signature);
        //给用户提供data和signature,publicKeyStr写到app端
        //但是使用hook技术，或者修改smail重新打包也能验签通过
        boolean isVerified = RSA2Util.verify(data, signature, publicKeyStr);
        Log.e("chen","验签结果: " + isVerified);
        if (isVerified){
            mVB.txtSign.setText("是否通过验签：通过" );
        } else {
            mVB.txtSign.setText("是否通过验签：未通过" );
        }
    }

}
